package com.uzhie.web.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uzhie.web.bean.PageBean;
import com.uzhie.web.bean.PayloadBean;
import com.uzhie.web.bean.ResponseBean;
import com.uzhie.web.bean.ResponseBodyBean;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * Created by TangFei on 2018/8/16.
 */
public class MyPayloadAspect {

    private Logger logger = Logger.getLogger(getClass());

    public ResponseBean run(ProceedingJoinPoint point) {
        logger.info("enter MyPayloadAspect method run");
        Object[] reqArgs = point.getArgs();
        JSONObject requestObj = JSONObject.parseObject(JSON.toJSONString(reqArgs[0]), JSONObject.class);
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        ResponseBean responseBean = new ResponseBean();
        responseBean.setRequestId(requestObj.getString("requestId"));
        responseBean.setRequestMethod(requestObj.getString("requestMethod"));
        responseBean.setResponseCode(200);
        responseBean.setResponseMsg("OK");
        Class<?> returnType = method.getReturnType();
        if (returnType.equals(PayloadBean.class)) {
            Object[] methodArgs = new Object[method.getParameterTypes().length];
            for (int i = 0; i < method.getParameterTypes().length; i++) {
                if (method.getParameterTypes()[i] == JSONObject.class) {
                    methodArgs[i] = requestObj.getJSONObject("requestBody");
                } else if (method.getParameterTypes()[i] == PageBean.class) {
                    methodArgs[i] = requestObj.getObject("page", PageBean.class);
                } else {
                    continue;
                }
            }
            try {
                Object proceedObj = point.proceed(methodArgs);
                responseBean.setResponseBody((ResponseBodyBean) proceedObj);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                responseBean.setResponseCode(500);
                responseBean.setResponseMsg(throwable.getMessage());
            }
        } else {
            responseBean.setResponseCode(500);
            responseBean.setResponseMsg("方法错误！");
        }
        return responseBean;
    }

}
